//
//  ChatTableViewController.m
//  projectOfTeamSample
//
//  Created by lanou3g on 15/11/18.
//  Copyright © 2015年 liukai. All rights reserved.
//

#import "ChatTableViewController.h"
#import "ChatTableViewCell.h"
//
#import "ChatMassage.h"
#import "ChatDB.h"
#import "ChatModel.h"
//聊天的头文件
#import <AVUser.h>
@interface ChatTableViewController () <UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>
@property (nonatomic,strong) UITableView *tableview;
//文本框和发送按钮的背景视图
@property (nonatomic,strong) UIView *backView;
//文本框
@property (nonatomic,strong) UITextField *textField;
//按钮
@property (nonatomic,strong) UIButton *sendButton;
//当前登录的用户名
@property (nonatomic,strong)  AVUser *currentUser ;




@end

@implementation ChatTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //一个tableView
    self.tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 60) style:UITableViewStyleGrouped];
    self.tableview.backgroundColor = [UIColor orangeColor];
    [self.view addSubview:self.tableview];
    
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    
    //一个发送信息的输入框
    [self SendMassagetextField];
    
    //注册
    [self.tableview registerClass:[ChatTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    //添加键盘的监听事件
    //当键盘要弹出的时候的监听事件
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillappear:) name:UIKeyboardWillShowNotification object:nil];
//    //键盘隐藏的时候的监听事件
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillDisappear:) name:UIKeyboardWillHideNotification object:nil];
    //注册一个手势,在点击屏幕的时候收回键盘
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    [self.view addGestureRecognizer:tap];
    [self.view resignFirstResponder];
    
    
//    //array
//    ChatTableViewCell *cell = [[ChatTableViewCell alloc]init];
//    self.array = cell.array;
    
    //数据库的内容
    [[ChatDB manager]openChetDB];
    [[ChatDB manager]creatTable];
    [[ChatDB manager]seleteAll];
    
    self.array = [[NSMutableArray alloc] init];
    self.array = [NSMutableArray arrayWithArray:[[ChatDB manager] seleteAll]];
    
    //cell显示在最后一行
    
    if (self.array.count == 0) {
        
    }else{
        
        [self.tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.array.count -1 inSection:0] atScrollPosition:(UITableViewScrollPositionNone) animated:YES];
    }
    
   
}
#pragma mark -- 发送信息的文本框
- (void)SendMassagetextField{
    //手机的大小
    CGRect frame = [UIScreen mainScreen].bounds;
    
    //键盘的背景
    self.backView = [[UIView alloc]initWithFrame:CGRectMake(0, frame.size.height- 60, frame.size.width, 60)];
    [self.view addSubview:self.backView];
    //给背景框添加一个手势,上划的时候弹出键盘
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panAction)];
    [self.backView addGestureRecognizer:pan];
    
    //输入框
    self.textField = [[UITextField alloc]initWithFrame:CGRectMake(10, 15, frame.size.width - 70, 30)];
    //代理
    self.textField.delegate = self;
    //键盘的圆形边框
    self.textField.borderStyle = UITextBorderStyleLine;
   
    //输入框的差号,用于一次性删除输入框的内容
    self.textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    //在次编辑就清空
    self.textField.clearsOnBeginEditing = YES;
    //return键的样式
    self.textField.returnKeyType = UIReturnKeySend;
    [self.backView addSubview:self.textField];
    
    
    //一个button
    self.sendButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [self.sendButton setTitle:@"发送" forState:(UIControlStateNormal)];
    [self.sendButton addTarget:self action:@selector(sendButtonAction) forControlEvents:(UIControlEventTouchUpInside)];
    //sendButton.frame = CGRectMake(frame.size.width - textField.bounds.size.width - 10, 15, 30, 30) ;
        self.sendButton.frame = CGRectMake(frame.size.width  - 45, 15, 30, 30) ;
    [self.backView addSubview:self.sendButton];
    

    self.tableview.backgroundColor = [UIColor whiteColor];

    
    
}
#pragma mark -- 键盘出现和隐藏要实现的方法
//要在什么时候改变textfield呢?
//1.在点击textField的时候,就是在点击键盘准备输入的时候,要将输入框移到键盘的上面(是不是可以直接添加到键盘 的顶视图上???)
//2.点击发送按钮的时候,不需要收回键盘,要让用户继续输入下一条聊天
//3.点击return的时候,和点击button实现的方法是一样的
//4.点击tableView的时候要收回键盘
//5.滑动tableview的时候,不用收回键盘
//6.键盘上有一个收回键盘的按钮,有没有??

//添加监听,系统监听键盘是否弹出,计算view应该移动的位置



//计算键盘的高度???
//传入的(NSDictionary *)userInfo用于存放键盘的各种信息，其中UIKeyboardFrameEndUserInfoKey对应的存放键盘的尺寸信息，以CGRect形式取出。
- (CGFloat)keyboardEndingFrameHeight:(NSDictionary *)userInfo{
    CGRect keyboardEndingUncorrectedFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
    
    CGRect keyboardEndingFrame = [self.view convertRect:keyboardEndingUncorrectedFrame fromView:nil];
    
    return keyboardEndingFrame.size.height;
}

// 将rect由rect所在视图转换到目标视图view中，返回在目标视图view中的rect
//- (CGRect)convertRect:(CGRect)rect toView:(UIView *)view{
//    return rect;
//}
//// 将rect从view中转换到当前视图中，返回在当前视图中的rect
//- (CGRect)convertRect:(CGRect)rect fromView:(UIView *)view{
//    return rect;
//}

//最终返回的是键盘在当前视图中的高度。

//然后，根据键盘高度将当前视图向上滚动同样高度。
- (void)keyboardWillappear:(NSNotification *)notification{
    CGRect currenFrame = self.view.frame;
    CGFloat change = [self keyboardEndingFrameHeight:[notification userInfo]];
    currenFrame.origin.y = currenFrame.origin.y - change;
    self.view.frame = currenFrame;
   
}
//当键盘消失后,视图回复原装
-(void)keyboardWillDisappear:(NSNotification *)notification

{
    
    CGRect currentFrame = self.view.frame;
    
    CGFloat change = [self keyboardEndingFrameHeight:[notification userInfo]];
    
    currentFrame.origin.y = currentFrame.origin.y + change ;
    
    self.view.frame = currentFrame;
    
}

//点击return的方法
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.textField resignFirstResponder];
    [self sendMassageWithText:self.textField.text type:@"MyName"];
    
    [self sendMassageWithText:@"对,你是最棒的!" type:@"OtherName"];
    return YES;
}
#pragma mark -- 发送消息的方法
- (void)sendMassageWithText:(NSString *)text type:(NSString *)typestring{
    //清空数组
    [self.array removeAllObjects];
    //发送消息
    ChatMassage *message = [[ChatMassage alloc]init];
    // [message tomSendMessageToJerry];
    //添加数据
    [message SendMessageToOtherWithString:text OtherUserName:@"aaa"];
    //添加数据到数据库
    [[ChatDB manager]insertWithText:text WithId:typestring];

    
       //获取聊天记录
    self.array = [NSMutableArray arrayWithArray:[[ChatDB manager] seleteAll]];
    
    //为什么要先刷新数据,在让cell在最后一行呢
    //因为点击按钮以后,数组里就加了一个数据,但是cell并没有重用最新的,所以会导致数组越界
    //例如:一开始的数组里有10个数据,点击按钮以后,数组的数据就加到11个,但是cell还是10个
    [self.tableview reloadData];
    
    [self.tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.array.count -1 inSection:0] atScrollPosition:(UITableViewScrollPositionNone) animated:YES];
    
    self.textField.text = @"";
    
    

}
#pragma mark -- 发送按钮的点击方法
- (void)sendButtonAction{
    //收回键盘
    //[self.textField resignFirstResponder];
    
    [self sendMassageWithText:self.textField.text type:self.currentUser.username];
    
   // [self sendMassageWithText:@"对,你是最棒的!" type:@"OtherName"];
    
}
#pragma mark -- 收回键盘的手势
//点击屏幕收回键盘的手势
- (void)tapAction{
    [self.textField resignFirstResponder];
}
//滑动textfield弹出键盘的手势
- (void)panAction{
    [self.textField becomeFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return 1;
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.array.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ChatTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    if (cell == nil) {
        cell = [[ChatTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    else{
        for (UIView *cellView in cell.subviews) {
            [cellView removeFromSuperview];
        }
    }
    //self.array = [[ChatDB manager]seleteAll];
    
    ChatModel *model = [[ChatModel alloc] init];
    model = self.array[indexPath.row];
    //
    //创建头像
    if (self.currentUser.username == nil) {
        NSLog(@"滚去登录");
        return cell;
          }else{
        UIImageView *photo ;
        if ([model.client isEqualToString:self.currentUser.username])
        {
            photo = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.bounds.size.width-60, 10, 50, 50)];
            [cell addSubview:photo];
            photo.image = [UIImage imageNamed:@"photo1"];
        
            [cell addSubview:[cell bubbleViewWithText:model.chatMassage form:YES withPosition:65]];
        }else{
            photo = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 50, 50)];
            [cell addSubview:photo];
            photo.image = [UIImage imageNamed:@"photo"];
        
            [cell addSubview:[cell bubbleViewWithText:model.chatMassage form:NO withPosition:65]];
                }

    
    
    }
    return cell;
    
}
//设置行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    ChatModel *model = [self.array objectAtIndex:indexPath.row];
    
    UIFont *font = [UIFont systemFontOfSize:14];
    

    CGSize size = [model.chatMassage sizeWithFont:font constrainedToSize:CGSizeMake(180.0f, 20000.0f) lineBreakMode:NSLineBreakByWordWrapping];
    

    
    return size.height+44;
}
#pragma mark -- 聊天

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
